package org.example.java.util.concurrency;

import java.util.concurrent.locks.LockSupport;

/**
 * @author juntao zhang
 */
public class SleepInterrupt implements Runnable {

  private Object lock = new Object();

  public void run() {
    try {
      System.out.println("in run() - about to block");
      synchronized (lock){
        lock.wait(); // wake up will in catch, isInterrupted() will be false ,because of when in catch the flag will be reset
      }
      LockSupport.park();//wake will not in catch
      System.out.println("isInterrupted->" + Thread.currentThread().isInterrupted());
//      Thread.sleep(5000);
      System.out.println("in run() - woke up");
    } catch (Exception e) {
//      Thread.currentThread().interrupt();
//      System.out.println(Thread.currentThread().isInterrupted());
//      System.out.println("interrupted=>" + Thread.interrupted());
//      try {
//        Thread.sleep(1000);
//      } catch (InterruptedException e1) {
//        e1.printStackTrace();
//      }
      System.out.println("in run() InterruptedException");
      return;
    }
    System.out.println("in run() - leaving normally");
  }


  public static void main(String[] args) {
    SleepInterrupt si = new SleepInterrupt();
    Thread t = new Thread(si);
    t.start();
    //主线程休眠2秒，从而确保刚才启动的线程有机会执行一段时间
    System.out.println("in main() - interrupting other thread");
    //中断线程t
    sleep(100);
//    t.interrupt();//Thread.currentThread().isInterrupted() will be true
    LockSupport.unpark(t); //Thread.currentThread().isInterrupted() will be false
    System.out.println("in main()->" + t.isInterrupted());
    System.out.println("in main() - leaving");


  }

  public static void sleep(int i) {
    try {
      Thread.sleep(i);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
